<template>
  <div class="p-6 space-y-6">
    <!-- Welcome Section -->
    <div class="bg-white rounded-lg shadow-sm p-6">
      <h2 class="text-2xl font-bold text-gray-800 mb-4">
        👋 Welcome to SideX
      </h2>
      <p class="text-gray-600 mb-4">
        Your intelligent Chrome extension side panel companion.
      </p>

      <!-- Quick Stats -->
      <div class="grid grid-cols-2 gap-4">
        <div class="bg-blue-50 p-4 rounded-lg">
          <div class="text-2xl font-bold text-blue-600">
            {{ tabsCount }}
          </div>
          <div class="text-sm text-gray-600">
            Open Tabs
          </div>
        </div>
        <div class="bg-green-50 p-4 rounded-lg">
          <div class="text-2xl font-bold text-green-600">
            {{ extensionStatus }}
          </div>
          <div class="text-sm text-gray-600">
            Status
          </div>
        </div>
      </div>
    </div>

    <!-- Current Tab Info -->
    <div
      v-if="currentTab"
      class="bg-white rounded-lg shadow-sm p-6"
    >
      <h3 class="text-lg font-semibold text-gray-800 mb-4">
        📄 Current Tab
      </h3>
      <div class="space-y-3">
        <div>
          <label class="text-sm font-medium text-gray-500">Title:</label>
          <p class="text-gray-800">
            {{ currentTab.title }}
          </p>
        </div>
        <div>
          <label class="text-sm font-medium text-gray-500">URL:</label>
          <p class="text-gray-800 break-all">
            {{ currentTab.url }}
          </p>
        </div>
        <div class="flex gap-2">
          <button
            class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
            :disabled="isAnalyzing"
            @click="analyzeCurrentPage"
          >
            {{ isAnalyzing ? 'Analyzing...' : 'Analyze Page' }}
          </button>
          <button
            class="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
            @click="refreshTabInfo"
          >
            Refresh
          </button>
        </div>
      </div>
    </div>

    <!-- Page Analysis Results -->
    <div
      v-if="pageAnalysis"
      class="bg-white rounded-lg shadow-sm p-6"
    >
      <h3 class="text-lg font-semibold text-gray-800 mb-4">
        🔍 Page Analysis
      </h3>
      <div class="space-y-4">
        <div>
          <label class="text-sm font-medium text-gray-500">Word Count:</label>
          <span class="ml-2 text-gray-800">{{ pageAnalysis.wordCount }}</span>
        </div>

        <div v-if="pageAnalysis.headings.length > 0">
          <label class="text-sm font-medium text-gray-500">Headings:</label>
          <ul class="mt-2 space-y-1">
            <li
              v-for="(heading, index) in pageAnalysis.headings.slice(0, 5)"
              :key="index"
              class="text-sm text-gray-700 pl-2 border-l-2 border-gray-200"
            >
              {{ heading }}
            </li>
          </ul>
        </div>

        <div v-if="pageAnalysis.links.length > 0">
          <label class="text-sm font-medium text-gray-500">Links ({{ pageAnalysis.links.length }}):</label>
          <div class="mt-2 space-y-1">
            <div
              v-for="(link, index) in pageAnalysis.links.slice(0, 3)"
              :key="index"
              class="text-sm p-2 bg-gray-50 rounded"
            >
              <div class="font-medium text-gray-800">
                {{ link.text }}
              </div>
              <div class="text-gray-600 text-xs break-all">
                {{ link.href }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Recent Activity -->
    <div class="bg-white rounded-lg shadow-sm p-6">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">
        📊 Recent Activity
      </h3>
      <div
        v-if="recentActivity.length === 0"
        class="text-gray-500 text-center py-4"
      >
        No recent activity
      </div>
      <div
        v-else
        class="space-y-2"
      >
        <div
          v-for="(activity, index) in recentActivity"
          :key="index"
          class="flex items-center justify-between p-3 bg-gray-50 rounded"
        >
          <div>
            <div class="font-medium text-gray-800">
              {{ activity.action }}
            </div>
            <div class="text-sm text-gray-600">
              {{ activity.timestamp }}
            </div>
          </div>
          <div class="text-sm text-gray-500">
            {{ activity.details }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

// Define types
interface TabInfo {
  title: string;
  url: string;
  id: number;
}

interface PageAnalysisResult {
  wordCount: number;
  headings: string[];
  links: Array<{ text: string; href: string }>;
}

// Reactive data
const currentTab = ref<TabInfo | null>(null);
const pageAnalysis = ref<PageAnalysisResult | null>(null);
const isAnalyzing = ref(false);
const tabsCount = ref(0);
const extensionStatus = ref('Active');

const recentActivity = ref([
  {
    action: 'Extension Installed',
    timestamp: new Date().toLocaleTimeString(),
    details: 'Welcome to SideX!'
  }
]);

// Methods
const getCurrentTabInfo = async () => {
  try {
    // Get current active tab
    const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
    if (tab) {
      currentTab.value = {
        title: tab.title || 'Untitled',
        url: tab.url || '',
        id: tab.id || 0
      };
    }

    // Get all tabs count
    const allTabs = await chrome.tabs.query({});
    tabsCount.value = allTabs.length;
  } catch (error) {
    console.error('Error getting tab info:', error);
  }
};

const analyzeCurrentPage = async () => {
  if (!currentTab.value?.id) return;

  isAnalyzing.value = true;
  try {
    // Send message to content script to analyze page
    const response = await chrome.tabs.sendMessage(currentTab.value.id, {
      type: 'ANALYZE_PAGE'
    });

    if (response) {
      pageAnalysis.value = response;
      recentActivity.value.unshift({
        action: 'Page Analyzed',
        timestamp: new Date().toLocaleTimeString(),
        details: `${response.wordCount} words found`
      });
    }
  } catch (error) {
    console.error('Error analyzing page:', error);
    recentActivity.value.unshift({
      action: 'Analysis Failed',
      timestamp: new Date().toLocaleTimeString(),
      details: 'Could not analyze page'
    });
  } finally {
    isAnalyzing.value = false;
  }
};

const refreshTabInfo = () => {
  getCurrentTabInfo();
  recentActivity.value.unshift({
    action: 'Tab Info Refreshed',
    timestamp: new Date().toLocaleTimeString(),
    details: 'Information updated'
  });
};

// Initialize
onMounted(() => {
  getCurrentTabInfo();
});
</script>

<style scoped>
/* Component-specific styles */
.break-all {
  word-break: break-all;
}
</style>